from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort

from flaskr.auth import login_required
from flaskr.models.schema import db, Post, User

bp = Blueprint('blog', __name__)

@bp.route('/')
def index():    
    posts = db.session.query(
        Post.id, Post.title, Post.body, Post.created, Post.author_id, User.username
    ).join(
        User, Post.author_id == User.id
    ).order_by(
        Post.created.desc()
    ).all()
    return render_template('blog/index.html', posts=posts)


@bp.route('/create', methods=('GET', 'POST'))
@login_required
def create():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:        
            new_post = Post(title=title, body=body, author_id=g.user.id)
            db.session.add(new_post)
            try:
                db.session.commit()
            except Exception as e:
                error = f"Error adding Post {title}: {str(e)}"
                db.session.rollback()
            else:
                return redirect(url_for('blog.index'))

    return render_template('blog/create.html')


@bp.route('/<int:id>/update', methods=('GET', 'POST'))
@login_required
def update(id):
    post = Post.query.get(id)

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            post.title = title
            post.body = body
            try:
                db.session.commit()
            except Exception as e:
                print(f"Error updating Post {title}: {str(e)}")
                db.session.rollback()
            return redirect(url_for('blog.index'))

    return render_template('blog/update.html', post=post)


@bp.route('/<int:id>/delete', methods=('POST',))
@login_required
def delete(id):
    post = Post.query.get(id)
    if post:
        db.session.delete(post)
        try:
            db.session.commit()
        except Exception as e:
            print(f"Error deleting Post {id}: {str(e)}")
            db.session.rollback()
    else:
        print(f"Post id {id} doesn't exist.")
    
    return redirect(url_for('blog.index'))